package com.dex4d.ui.main.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.AppToolbarBaseFragment;
import com.dex4d.core.CustomApplication;
import com.dex4d.core.ITabFragment;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.RequestParamObj;
import com.dex4d.model.User;
import com.dex4d.ui.main.activity.RequestAccount;
import com.dex4d.ui.main.adapter.HomeAdapter;
import com.dex4d.ui.main.model.AccountCoin;
import com.dex4d.ui.main.model.TokenContract;
import com.dex4d.ui.main.model.TokenDetail;
import com.dex4d.ui.main.socket.RPC;
import com.dex4d.ui.main.socket.RPCRequest;
import com.dex4d.utils.BaseUtils;
import com.dex4d.utils.MoneyUtils;
import com.framework.util.DisplayUtil;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.functions.Func1;

/**
 * Created by chengyuchun on 2018/10/19.
 */
public class TabMainFragment extends AppToolbarBaseFragment implements ITabFragment {

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout refreshLayout;

    @BindView(R.id.rv_home)
    RecyclerView recyclerView;

    HomeAdapter adapter;
    RPCRequest rpcRequest;

    Map<String, TokenContract> contractMap;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_main;
    }

    @Override
    protected void initVariables() {

        ((AppToolBarBaseActivity) mContext).hideBackView();

        contractMap = new HashMap<>();
        adapter = new HomeAdapter(getActivity(), recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());

        HorizontalDividerItemDecoration decoration =
                new HorizontalDividerItemDecoration
                        .Builder(getActivity())
                        .color(Color.TRANSPARENT)
                        .size(DisplayUtil.dip2px(getActivity(), 10))
                        .visibilityProvider(adapter)
                        .build();

        recyclerView.addItemDecoration(decoration);

        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateData(false);
            }
        });

    }

    @Override
    protected void loadData() {
        updateData(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (rpcRequest == null) {
            rpcRequest = new RPCRequest("getDetails");
        }
        CustomApplication.getClient().sendRpcRequest(rpcRequest);
        updateData(false);
    }

    void updateData(boolean isLoading) {
        final RequestParamObj requestParam = new RequestParamObj();
        requestParam.setId(2);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.GATEWAY_VAULTOVERVIEW);
        List<RequestAccount> list = new ArrayList<>();
        list.add(new RequestAccount(User.getInstance().getAddress(), MoneyUtils.getCurrencyCode()));
        requestParam.setParams(list);

        JsonApiWrapper
                .serviceApi()
                .gatewayMainVaultOverview(requestParam)
                .compose(new DefaultTransformer<HttpResult<AccountCoin>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<AccountCoin>>(getActivity(), isLoading) {
                    @Override
                    public void onNext(HttpResult<AccountCoin> result) {
                        adapter.updateTopData(result.getResult());
                        refreshLayout.setRefreshing(false);
                    }
                });
    }


    @Override
    public void onMenuItemClick() {

    }

    @Override
    public Fragment getFragment() {
        return this;
    }

    @Override
    public String getTitle() {
        return null;
    }

    @Override
    protected void initToolbar(AppToolBarBaseActivity mContent) {
        super.initToolbar(mContent);
        mContent.showTitle(getString(R.string.address) + ":" + BaseUtils.formatAddress(User.getInstance().getAddress()));
        mContent.hideBackView();
        mContent.getToolbarRight().setVisibility(View.VISIBLE);
    }

    /**
     * 更新列表
     *
     * @param rpc
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void updateTokenList(RPC rpc) {
        if (rpc != null && rpc.params != null && rpc.params.result != null) {
            if (TextUtils.equals(rpc.tag, rpcRequest.tag)) {
                if (contractMap == null || contractMap.isEmpty()) {
                    tokenTables(rpc.params.result);
                } else {
                    parse(rpc.params.result);
                }
            }
        }
    }

    /**
     * 处理代币列表
     *
     * @param list
     */
    private void tokenTables(final List<TokenDetail> list) {
        //请求此接口获取token列表
        final RequestParam requestParam2 = new RequestParam();
        requestParam2.setId(2);
        requestParam2.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam2.setMethod(IConstants.GATEWAY_GETTOKENTABLES);
        requestParam2.setParams(new ArrayList<String>());

        JsonApiWrapper
                .serviceApi()
                .getTokenTables(requestParam2)
                .map(new Func1<HttpResult<List<TokenContract>>, List<TokenContract>>() {
                    @Override
                    public List<TokenContract> call(HttpResult<List<TokenContract>> result) {
                        CustomApplication.getDb().tokenContractDao().insertAll(result.getResult());
                        return result.getResult();
                    }
                })
                .compose(new DefaultTransformer<List<TokenContract>>())
                .subscribe(new ProgressSubscriber<List<TokenContract>>(getActivity(), false) {
                    @Override
                    public void onNext(List<TokenContract> result) {
                        for (TokenContract temp : result) {
                            contractMap.put(temp.name, temp);
                        }
                        parse(list);
                    }
                });

    }

    /**
     * 获取游戏图标
     *
     * @param list
     */
    private void parse(List<TokenDetail> list) {
        for (TokenDetail detail : list) {
            TokenContract contract = contractMap.get(detail.symbol);
            if (contract != null) {
                if(contract.state == 4){
                    //标记清退状态不予显示
                    list.remove(detail);
                }else {
                    detail.state = contract.state;
                }
                detail.logo = contract.icon_app;
                detail.ambassador_begin = contract.ambassador_begin;
                detail.ambassador_end = contract.ambassador_end;
                detail.offline_time = contract.offline_time;
            }
        }
        adapter.updateTokenData(list);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
